-- ForcePress
-- create by zouyb
-- 3Dtouch相关处理函数

-- 按压力度，分为四挡，第四档为最用力
FORCE_GRADE_NONE = 0;
FORCE_GRADE_1    = 1;
FORCE_GRADE_2    = 2;
FORCE_GRADE_3    = 3;
FORCE_GRADE_4    = 4;

-- 处理用力按
function handleForcePress(sender, eventType, callback, cancelCallback)
    if SIMULATE_3D_TOUCH == 1 then
        return handleSimulateForcePress(sender, eventType, callback, cancelCallback);
    end

    if eventType == ccui.TouchEventType.began then
        sender.isForcePress = false;
	elseif eventType == ccui.TouchEventType.moved then
		local force = sender:getForce();

		local forceGrade = FORCE_GRADE_NONE;
		if force > 20 and force <= 40 then
			forceGrade = FORCE_GRADE_1;
		elseif force > 40 and force <= 60 then
			forceGrade = FORCE_GRADE_2;
		elseif force > 60 and force <= 80 then
			forceGrade = FORCE_GRADE_3;
		elseif force > 80 and force <= 100 then
			forceGrade = FORCE_GRADE_4;
		else 
			-- 没触发
		end
	
		if forceGrade > FORCE_GRADE_NONE then
			sender.isForcePress = true;
			callback(forceGrade);
			return true;
		end
	elseif eventType == ccui.TouchEventType.canceled
		or eventType == ccui.TouchEventType.ended then
		
		if sender.isForcePress == true then
			if cancelCallback then cancelCallback(); end
			return true;
		end
	end

	return false;
end

-- 模拟3Dtouch
function handleSimulateForcePress(sender, eventType, callback, cancelCallback)
    local function timeout(duration)
        local force = duration / 4 * 100;

        local forceGrade = FORCE_GRADE_NONE;
        if force > 20 and force <= 40 then
            forceGrade = FORCE_GRADE_1;
        elseif force > 40 and force <= 60 then
            forceGrade = FORCE_GRADE_2;
        elseif force > 60 and force <= 80 then
            forceGrade = FORCE_GRADE_3;
        elseif force > 80 and force <= 100 then
            forceGrade = FORCE_GRADE_4;
        else 
            -- 没触发
        end

        if forceGrade > FORCE_GRADE_NONE then
            sender.isForcePress = true;
            callback(forceGrade);
        end        
    end

    if eventType == ccui.TouchEventType.began then
        sender.isForcePress = false;
        performWithDelay(sender, function() 
            timeout(1);  end, 1);
        performWithDelay(sender, function() 
            timeout(2);  end, 2);
        performWithDelay(sender, function() 
            timeout(3);  end, 3);
        performWithDelay(sender, function() 
            timeout(4);  end, 4);
    elseif eventType == ccui.TouchEventType.canceled
        or eventType == ccui.TouchEventType.ended then
        sender:stopAllActions();    
        if sender.isForcePress == true then
            if cancelCallback then cancelCallback(); end
            return true;
        end
    end

    return false;
end


